<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use app\index\common;
use app\index\controller\Sms\AliYunSms;
use think\Cookie;
use think\Config;
use app\index\controller\Log\OperationLog as OL;

use app\index\plugin\yeepay\YopClient3;
use app\index\plugin\yeepay\YopRequest;
use app\index\plugin\yeepay\Util\YopSignUtils;

/**
 * 商户入驻类
 */
class Merchant extends Controller
{
	//申请实名认证的商户列表
	public function list(Request $request)
	{
		$postData = $request->post();
		$field = ['m.id, m.merFullName,m.merShortName,m.legalName,u.id user_id,u.phone,b.is_auth,m.create_time'];
		$merchants = Db::table('merchant')
					->alias('m')
					->join('merchant_resource_qiniu mr','mr.merchant_id = m.id','LEFT')
					->join('users u','u.id = m.user_id','LEFT')
					->join('business b', 'b.business_id = u.id', 'LEFT')
					->where(['m.state' => 0])
					->field($field)
					->select();

		$page = isset($postData['page']) ? $postData['page'] : 1;
		$merchantsIdentify = [];
		if(isset($postData['is_auth']) && $postData['is_auth'] != ''){
			foreach ($merchants as $key => $merchant) {
				if($merchant['is_auth'] == $postData['is_auth']){
					$merchantsIdentify [] = $merchant;
				}
			}
			return ReturnData::ok(['total'=>count($merchantsIdentify), 'list' => array_slice($merchantsIdentify,($page-1)*20, 20)]);
		}
		return ReturnData::ok(['total'=>count($merchants),'list' => array_slice($merchants,($page-1)*20, 20)]);
	}

	//商户的具体申请信息
	public function detail(Request $request)
	{
		$postData = $request->post();
		$rules = [
            "id"	=> "require",
		];

		if($this->validate($postData, $rules) !== true)
		{
			return ReturnData::error(10001,$this->validate($postData, $rules));
		}
		$merchant = Db::table('merchant')->where(['id' => $postData['id']])->find();
		if($merchant == null){
			return ReturnData::error(10001,'该用户非商家账号');
		}
		$merchant_resources = Db::table('merchant_resource')->where(['merchant_id' => $postData['id']])->find();
		if($merchant_resources == null){
			return ReturnData::error(10001,'该商家未上传任何资料');
		}
		$select = [
			'm.id,m.user_id,m.requestNo, m.merFullName, m.merShortName,m.merCertType,m.merCertNo,m.legalName,
			m.legalIdCard,a.Name merProvince, a2.Name merCity, a3.Name merDistrict, m.merAddress,m.merContactName,
			m.merContactPhone,m.merContactEmail, m.taxRegistCert,m.accountLicense,m.orgCode,m.isOrgCodeLong,
			m.orgCodeExpiry,m.cardNo,b.name headBankCode,a4.Name bankProvince,a5.Name bankCity,m.create_time,
			mr.IDCARD_FRONT,mr.IDCARD_BACK,mr.CORP_CODE,mr.TAX_CODE,mr.ORG_CODE,mr.UNI_CREDIT_CODE,mr.OP_BANK_CODE,mr.SETTLE_BANKCARD,mr.HAND_IDCARD,mr.HAND_BANKCARD'
		];
		$merchantInfo = Db::table('merchant m')
						->join('merchant_resource mr','mr.merchant_id = m.id','LEFT')
						->join('address a','a.ID = m.merProvince','LEFT')
						->join('address a2','a2.ID = m.merCity','LEFT')
						->join('address a3','a3.ID = m.merDistrict','LEFT')
						->join('bank b','b.code = m.headBankCode','LEFT')
						->join('address a4','a4.ID = m.bankProvince','LEFT')
						->join('address a5','a5.ID = m.bankCity','LEFT')
						->where(['m.id' => $postData['id'],'m.state' => 0])
						->field($select)
						->find();
		return ReturnData::ok($merchantInfo);
	}

	//实名认证
	public function identify(Request $request)
	{
		$postData = $request->post();
		$rules = [
            "user_id"						=> "require",
            "WECHAT_OPENID_HOME_PAGE" 		=> "require",
            "WECHAT_OPENID_PRODUCT_PAGE"	=> "require",
            "WECHAT_OPENID_PAYMENT_PROCESS" => "require",
		];

		if($this->validate($postData, $rules) !== true)
		{
			return ReturnData::error(10001,$this->validate($postData, $rules));
		}
		$merchant = Db::table('merchant')->where(['user_id' => $postData['user_id']])->find();
		if($merchant == null){
			return ReturnData::error(10001,'该用户非商家账号');
		}
		$merchant_resources = Db::table('merchant_resource')->where(['merchant_id' => $merchant['id']])->find();
		if($merchant_resources == null){
			return ReturnData::error(10001,'该商家未上传任何资料');
		}
		// 七牛图片链接保存数据库
		$qiniuConfig =  Config::get('qiniu');
		if(Db::table('merchant_resource_qiniu')->where('user_id',$postData['user_id'])->find())
		{
			Db::table('merchant_resource_qiniu')
			->where('user_id',$postData['user_id'])
			->update([
						'WECHAT_OPENID_HOME_PAGE' 	 	=> $qiniuConfig['merchantDomain'].$postData['WECHAT_OPENID_HOME_PAGE']['img'],
						'WECHAT_OPENID_PRODUCT_PAGE' 	=> $qiniuConfig['merchantDomain'].$postData['WECHAT_OPENID_PRODUCT_PAGE']['img'],
						'WECHAT_OPENID_PAYMENT_PROCESS' => $qiniuConfig['merchantDomain'].$postData['WECHAT_OPENID_PAYMENT_PROCESS']['img'],
					]);
		}else{
			ReturnData::error(1001,'商家实名认证信息不全');
		}
		// 图片上传易宝
		$yeePayConfig =  Config::get('yeepay');
		$uplodImages =  [
			'WECHAT_OPENID_HOME_PAGE' 		=> $postData['WECHAT_OPENID_HOME_PAGE']['_file'],
			'WECHAT_OPENID_PRODUCT_PAGE' 	=> $postData['WECHAT_OPENID_PRODUCT_PAGE']['_file'],
			'WECHAT_OPENID_PAYMENT_PROCESS' => $postData['WECHAT_OPENID_PAYMENT_PROCESS']['_file'],
		];
		$uploadResult = $this->uploadYeepayImage($uplodImages, $yeePayConfig, $postData['user_id']);
		if($uploadResult['result'] == null){
			return ReturnData::error(1005,"上传易宝平台出错",$uploadResult);
		}
		//上传资料到易宝提交实名认证
		$merchant_resources = Db::table('merchant_resource')->where(['merchant_id' => $merchant['id']])->find();
		$identifyResult = $this->enterprisereginfoadd($yeePayConfig, $merchant, $merchant_resources);  
   		return ReturnData::ok($identifyResult);
	}

	public function uploadYeepayImage($uplodImages, $yeePayConfig, $user_id)
	{
		foreach ($uplodImages as $key => $uplodImage) {
			if($key == 'WECHAT_OPENID_HOME_PAGE' || $key == 'WECHAT_OPENID_PRODUCT_PAGE' || $key == 'WECHAT_OPENID_PAYMENT_PROCESS')
			$uploadResult = $this->uploadYeepay($key, $uplodImage, $yeePayConfig, $user_id);
			if($uploadResult['result'] == null){
				return $uploadResult;
			}
		}
		
	}

	public function uploadYeepay($key, $file, $yeePayConfig, $user_id)
	{
		$request = new YopRequest("OPR:10014929805", $yeePayConfig['private_key'], "https://open.yeepay.com/yop-center", $yeePayConfig['yop_public_key']);
  
       	$request->addParam("fileType", "IMAGE");
       	$request->addParam("_file", $file);
	   
       	$response = YopClient3::upload("/rest/v1.0/file/upload", $request);
      //取得返回结果
    	$data = common::object_array($response);
 
    	if($data['result'] == null){
    		return $data;
    	}else{
    		Db::table('merchant_resources')->where('user_id',$user_id)->update([$key => $data['result']['files'][0]['fileLocation']]);
    	}
	}

	public function enterprisereginfoadd($yeePayConfig,$merchant,$merchant_resources)
	{
		     
	    $request = new YopRequest("OPR:10014929805", $yeePayConfig['private_key'], "https://open.yeepay.com/yop-center",$yeePayConfig['yop_public_key']);
	    $productInfo = '{
	    				// 支付产品
	    				"payProductMap":{
	    					//用户扫码支付
	    					"USER_SCAN_PAY":{
	    						//支付银行
	    						"dsPayBankMap":{
	    								//银联主扫
										"UPOP_ATIVE_SCAN":	 {"rateType":"PERCENTAGE","rate":"0.48"},
										//支付宝支付
										"ALIPAY":         	 {"rateType":"PERCENTAGE","rate":"0.48"},
										//WAP 微信主扫支付
										"WECHAT_ATIVE_SCAN": {"rateType":"PERCENTAGE","rate":"0.48"},
										//京东主扫
										"JD_ATIVE_SCAN":	 {"rateType":"PERCENTAGE","rate":"0.48"}
									}
							},
							// 公众号支付
							"OFFICIAL_ACCOUNT_PAY":{
								//支付银行
								"dsPayBankMap":{
									//WAP 微信公众号支付
									"WECHAT_OPENID":{"rateType":"PERCENTAGE","rate":"0.48"}
								},
								//推荐关注公众号服务号
								"recommendOfficialAccAppId":"23424",
								//公众号服务号
								"officialAccAppId":"3234234",
								//商户微信号
								"weChatId":"303408568",
								//公众号支付授权目录
								"officialAccAuthorizeDirectory": "http://www.baidu.com"
			
							},
							//钱包支付 H5
							"EWALLETH5":{
								"dsPayBankMap":{
									//支付宝 H5
									"ALIPAY_H5":{"rateType":"PERCENTAGE","rate":"0.48"}
			
								}
			
							}
		
						},
						//支付场景
						"payScenarioMap":{
							"H5_ACCESS":{"webUrl":"http://www.jiaboyan.com"}, //H5 网页接入
							"OFFICIAL_ACCOUNT_ACCESS":{},	//公众号接入
							"WEB_ACCESS":{"webUrl":"http://www.jiaboyan.com","icp":"111111111"}, // WEB 网站接入
							"APP_ACCESS":{"appName":"jiajunAPP","appDownloadUrl":"324234111111111111111"}, //APP 接入
							"FACE_TO_FACE_ACCESS":{} //面对面接入
		
						}
	
					}';
		$fileInfo = [
			[
				"quaType" => "IDCARD_FRONT",
 				"quaUrl"  => $merchant_resources['IDCARD_FRONT']
			],
			[
				"quaType" => "IDCARD_BACK",
 				"quaUrl"  => $merchant_resources['IDCARD_BACK']
			],
			[
				"quaType" => "CORP_CODE",
 				"quaUrl"  => $merchant_resources['CORP_CODE']
			],
			[
				"quaType" => "TAX_CODE",
 				"quaUrl"  => $merchant_resources['TAX_CODE']
			],
			[
				"quaType" => "ORG_CODE",
 				"quaUrl"  => $merchant_resources['ORG_CODE']
			],
			[
				"quaType" => "UNI_CREDIT_CODE",
 				"quaUrl"  => $merchant_resources['UNI_CREDIT_CODE']
			],
			[
				"quaType" => "OP_BANK_CODE",
 				"quaUrl"  => $merchant_resources['OP_BANK_CODE']
			],
			[
				"quaType" => "SETTLE_BANKCARD",
 				"quaUrl"  => $merchant_resources['SETTLE_BANKCARD']
			],
			[
				"quaType" => "HAND_IDCARD",
 				"quaUrl"  => $merchant_resources['HAND_IDCARD']
			],
			[
				"quaType" => "HAND_BANKCARD",
 				"quaUrl"  => $merchant_resources['HAND_BANKCARD']
			],
			[
				"quaType" => "WECHAT_OPENID_HOME_PAGE",
 				"quaUrl"  => $merchant_resources['WECHAT_OPENID_HOME_PAGE']
			],
			[
				"quaType" => "WECHAT_OPENID_PRODUCT_PAGE",
 				"quaUrl"  => $merchant_resources['WECHAT_OPENID_PRODUCT_PAGE']
			],
			[
				"quaType" => "WECHAT_OPENID_PAYMENT_PROCESS",
 				"quaUrl"  => $merchant_resources['WECHAT_OPENID_PAYMENT_PROCESS']
			],
			
		];

		// $businessFunction = [];

		$notifyUrl = Config::get('url_api_root').'/merchant/notify';
		$merAuthorizeType = 'WEB_AUTHORIZE';

	    $request->addParam("parentMerchantNo", $yeePayConfig['parentMerchantNo']);
	    $request->addParam("requestNo", $merchant['requestNo']);
	    $request->addParam("merFullName", $merchant['merFullName']);
	    $request->addParam("merShortName", $merchant['merShortName']);
		$request->addParam("merCertType", $merchant['merCertType']);
	    $request->addParam("merCertNo", $merchant['merCertNo']);
	    $request->addParam("legalName", $merchant['legalName']); 
	    $request->addParam("legalIdCard", $merchant['legalIdCard']);
	    
	    $request->addParam("merLevel1No", $merchant['merLevel1No']);
	    $request->addParam("merLevel2No", $merchant['merLevel2No']);
	    $request->addParam("merProvince", $merchant['merProvince']);
	    $request->addParam("merCity", $merchant['merCity']);
	    $request->addParam("merDistrict", $merchant['merDistrict']);
	    $request->addParam("merAddress", $merchant['merAddress']);
		$request->addParam("merContactName", $merchant['merContactName']);
		$request->addParam("merContactPhone", $merchant['merContactPhone']);
	    $request->addParam("merContactEmail", $merchant['merContactEmail']);
	    $request->addParam("taxRegistCert", $merchant['taxRegistCert']);
	    $request->addParam("accountLicense", $merchant['accountLicense']);
	    $request->addParam("orgCode", $merchant['orgCode']);
	    $request->addParam("isOrgCodeLong", $merchant['isOrgCodeLong']);
	    $request->addParam("orgCodeExpiry", $merchant['orgCodeExpiry']);

	    $request->addParam("cardNo", $merchant['cardNo']);
	    $request->addParam("headBankCode", $merchant['headBankCode']);
	    $request->addParam("bankCode", $merchant['bankCode']);
	    $request->addParam("bankProvince", $merchant['bankProvince']);
	    $request->addParam("bankCity", $merchant['bankCity']);
	    $request->addParam("productInfo", $productInfo);
	    $request->addParam("fileInfo", json_encode($fileInfo));            
	    //$request->addParam("businessFunction", $merchant['businessFunction']);
	    $request->addParam("notifyUrl", $notifyUrl);
	    $request->addParam("merAuthorizeType", $merAuthorizeType);
	 
	    $response = YopClient3::post("/rest/v1.0/sys/merchant/enterprisereginfoadd", $request);
	    // return $response;
	    // if($response->validSign==1){
	    //     echo "返回结果签名验证成功!\n";
	    // }
	    //取得返回结果
	    $data=common::object_array($response);
	    
	    return $data;
	    
	 }

	 public function notify(Request $request)
	 {
	 	$data = $request->post();
	 	$yeePayConfig =  Config::get('yeepay');
	 	return YopSignUtils::decrypt($data['response'],$yeePayConfig['private_key'], $yeePayConfig['yop_public_key']);
	 }

}